<?php
/**
 * 购物车服务类
 * Created by PhpStorm.
 * User: Yui
 * Date: 2017/3/30 0030
 * Time: 10:39
 */
namespace common\services;

use Yii;
use common\library\comFun;
use common\models\Cart;

class CartSve extends BaseSve
{
    /**
     * 获取购物车列表
     * @param $Member
     * @return array
     */
    public function getCartList($Member):array
    {
        try {
            //纯sql查出所有购物车商品
            $list = Yii::$app->db->createCommand('SELECT c.cart_id,c.member_id,c.store_id,c.goods_id,c.goods_title,
                                              c.goods_price,c.buy_num,c.image,s.store_name FROM cart AS c 
                                              LEFT JOIN store AS s ON c.store_id = s.store_id WHERE c.member_id = :member_id')
                ->bindValue(':member_id', $Member->member_id)->queryAll();
            $storeArr = [];
            //循环处理数组，根据店铺划分
            foreach ($list as $item) {
                if (!isset($storeArr[$item['store_id']])) {
                    $storeArr[$item['store_id']] = [];
                    $storeArr[$item['store_id']]['store_name'] = $item['store_name'];
                    $storeArr[$item['store_id']]['store_id'] = $item['store_id'];
                    $storeArr[$item['store_id']]['goods_list'] = [];
                }
                array_push($storeArr[$item['store_id']]['goods_list'], $item);
            }
            return self::result('', 0, ['list' => $storeArr]);
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }

    }

    /**
     * 添加商品
     * @param string $goodsList = 1:1,3:1
     * @param $Member
     * @return array
     */
    public function addGoods(string $goodsList, $Member):array
    {
        //检查字符串是否为空
        if (!comFun::checkCartFormat($goodsList)) {
            return self::result('参数错误');
        }
        //处理字符串成数组
        $goodsList = comFun::cartStrToArr($goodsList);
        //检查商品
        foreach ($goodsList as $item) {

        }
    }

    /**
     * 更新购物车
     * @param $goodsList = 1:2,2:3
     * @param $Member
     * @return array
     */
    public function updateCart(string $goodsList, $Member):array
    {
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            //检查格式
            if (!comFun::checkCartFormat($goodsList)) {
                throw new \Exception('参数格式错误', -1);
            }
            //购物车格式字符串转成数组
            $goodsList = comFun::cartStrToArr($goodsList);
            //循环更新
            foreach ($goodsList as $item) {
                $rs = Cart::updateAll(
                    ['buy_num' => $item['buy_num']],
                    ['member_id' => $Member->member_id, 'goods_id' => $item['goods_id']]
                );
                if ($rs === false) {
                    throw new \Exception('修改失败', -1);
                }
            }
            $transaction->commit();
            return self::result('修改成功', 0);
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }

    /**
     * 删除购物车商品
     * @param string $goodsIds = 1,2,3
     * @param $Member
     * @return array
     */
    public function removeGoods(string $goodsIds, $Member):array
    {
        try {
            //检查格式
            if (!comFun::checkIdsFormat($goodsIds)) {
                throw new \Exception('参数格式错误', -1);
            }
            //转换成数组
            $goodsIdsArr = explode(',',$goodsIds);
            //移除
            return parent::batchRemove([
                'AND',
                ['=', 'member_id', $Member->member_id],
                ['in', 'goods_id', $goodsIdsArr]
            ]);
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }


    /**
     * 清空购物车
     * @param $Member
     * @return array
     */
    public function clear($Member):array
    {
        try {
            $rs = parent::batchRemove(['member_id' => $Member->member_id]);
            if ($rs['code'] === 0) {
                return self::result('清空成功', 0);
            } else {
                throw new \Exception('清空失败', -1);
            }
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }
}